#!/bin/bash

# ElasticSearch + Kibana 启动脚本
echo "🚀 启动 ElasticSearch + Kibana 服务..."

# 检查 Docker 是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ 错误: Docker 未运行，请先启动 Docker"
    exit 1
fi

# 检查 docker-compose 文件是否存在
if [ ! -f "docker-compose.yml" ]; then
    echo "❌ 错误: docker-compose.yml 文件不存在"
    exit 1
fi

# 设置必要的内核参数（Linux系统）
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "🔧 设置系统参数..."
    sudo sysctl -w vm.max_map_count=262144
fi

# 创建必要的目录
mkdir -p logs

# 启动服务
echo "📦 拉取并启动容器..."
docker-compose up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."

# 检查 ElasticSearch
echo "检查 ElasticSearch (http://localhost:9200)..."
if curl -s http://localhost:9200 > /dev/null; then
    echo "✅ ElasticSearch 启动成功"
    echo "📊 ElasticSearch 状态:"
    curl -s http://localhost:9200/_cluster/health?pretty | grep -E '"status"|"number_of_nodes"|"cluster_name"'
else
    echo "❌ ElasticSearch 启动失败"
fi

# 检查 Kibana
echo ""
echo "检查 Kibana (http://localhost:5601)..."
if curl -s http://localhost:5601/api/status > /dev/null; then
    echo "✅ Kibana 启动成功"
else
    echo "⏳ Kibana 仍在启动中，请稍等..."
fi

echo ""
echo "🎉 部署完成！"
echo "📍 访问地址:"
echo "   ElasticSearch: http://localhost:9200"
echo "   Kibana:        http://localhost:5601"
echo ""
echo "📝 常用命令:"
echo "   查看日志:     docker-compose logs -f"
echo "   停止服务:     docker-compose down"
echo "   重启服务:     docker-compose restart"
echo "   查看状态:     docker-compose ps"
